<?php


namespace Tbf\Bundle\AjkApiBundle\Listener;


use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Tbf\Bundle\AjkApiBundle\Controller\HtmlMessageController;
use Tbf\Bundle\TbfBundle\Exception\BusinessException;
use Tbf\Bundle\TbfBundle\Service\AnnotationsReader;

class HtmlMessageListener implements EventSubscriberInterface{
    /** @var  \Tbf\Bundle\TbfBundle\Service\AnnotationsReader */
    protected $annotation_reader;
    /** @var \Tbf\Bundle\AjkApiBundle\Controller\HtmlMessageController  */
    protected $controller;
    function __construct(AnnotationsReader $annotation_reader,HtmlMessageController $controller){
        $this->annotation_reader = $annotation_reader;
        $this->controller = $controller;
    }
    public static function getSubscribedEvents()
    {
        return array(
            KernelEvents::CONTROLLER=>array('filterAnnotation'),
            KernelEvents::EXCEPTION=>array('onKernelException'),
        );
    }
    function filterAnnotation(FilterControllerEvent $event){
        $ret = $this->annotation_reader
            ->getCallableAnnotation($event->getController(),'Tbf\Bundle\AjkApiBundle\Annotation\HtmlMessage');
        if ($ret===null){
            return;
        }
        $event->getRequest()->attributes->set('bzs_html_message',true);
    }
    function onKernelException(GetResponseForExceptionEvent $event){

        $exception = $event->getException();
        if (!$exception instanceof BusinessException){
            return;
        }
        if (!$event->getRequest()->attributes->get('bzs_html_message')){
            return;
        }
        $message = $exception->getMessage();
        $response = $this->controller->errorPage($message);
        $response->headers->set('X-Status-Code',200);
        $event->setResponse($response);
        $event->stopPropagation();
    }
}